# -*- coding: utf-8 -*-
from django.http import HttpResponse,Http404, HttpResponseRedirect, HttpResponseServerError
from django.template import Context, loader,defaultfilters
from django.forms.formsets import formset_factory
from django.shortcuts import get_object_or_404
from django.core.paginator import Paginator
from django.core.urlresolvers import reverse
from django.core import serializers
from django.utils import simplejson
from django.views.decorators.cache import cache_page
from settings import *
from apps.models import User,Language
from apps.blog.models import Profile,Post,PostDiggLog,Comment,Category
from apps.blog.form import CommentForm
from apps.templatetags import pagebase
from utils import formatter,function,mailer,uploader,logs
from utils.components import ExecuteState
from utils.dict import errorinfos
from utils.helper import view,convert
import traceback

def _get_template_path(template='home.html'):
    """
    summary:
        生成模板地址
    params:
        owner        博客主人Profile信息,用于取theme的
        template    页面模板文件
    """
    return 'blog/%s' % (template)

def _get_owner(owner_slug):
    owner = None
    if owner_slug != '':
        try:
            # 取博客主人的信息
            owner = Profile.objects.get(slug = owner_slug)
        except (Profile.DoesNotExist):
            # 用户还未开通博客
            pass
        except:
            logs.write(traceback)

    return owner

def _post_list(request,owner_slug,page_index=1,category_slug=None,tag_name=None):
    """
    summary:
        分页列表
    """
    owner = _get_owner(owner_slug)
    title = ''
    meta_keywords = ''
    meta_description = ''
    has_category = False
    has_tag_name = False
    posts = []
    
    try:
        url_format = reverse('blog_home',args=[owner.slug]) + '%s/'
        if category_slug:
            posts = Post.objects.filter(profile__user__id = owner.user.id, status = 1, category__slug = category_slug ).order_by('-stay_on_top','-addtime')
            
            category = Category.objects.get(slug = category_slug,profile__user__id = owner.user.id)
            url_format = reverse('blog_category',args=[owner.slug,category_slug]) + '%s/'
            if category:
                title = '%s - ' % (category.name)
                meta_description = title
                meta_keywords = title
            else:
                view.out_404()
        else:
            posts = Post.objects.filter(profile__user__id = owner.user.id, status = 1 ).order_by('-stay_on_top','-addtime')
                
        paginator = Paginator(posts,owner.page_size)
        pagebar = formatter.pagebar(paginator,page_index,owner.page_size,owner,url_format)
        posts = paginator.page(page_index).object_list
    except:
        logs.write(traceback)
        return view.out_unknow_error()

    data = {
            'current_profile': request.current_profile,
            'owner' : owner,
            'posts' : posts,
            'pagebar' : pagebar,
            'title' : title,
            'meta_keywords' : meta_keywords,
            'meta_description' : meta_description,
            'has_category' : has_category,            
            }

    template = _get_template_path('home.html')

    return view.out_page(template,data)

def home(request,owner_slug,page_index=1):
    """
    summary:
        博客主页
    """
    return _post_list(request, owner_slug, page_index)

def category(request,owner_slug,slug,page_index=1):
    """
    summary:
        分类页面
    """
    return _post_list(request, owner_slug, page_index,slug)


def post(request,owner_slug,slug):
    """
    summary:
        查看文章页面
    """
    owner = _get_owner(owner_slug)
    post = None
    # get post content
    try:
        post = Post.objects.get(profile__slug = owner_slug, slug = slug, status = 1)                
    except( (Post.DoesNotExist)):
        return view.out_404()
    except:
        logs.write(traceback)
        return view.out_unknow_error()
    
    # check is digged
    is_digged = False
    client_ip_int = convert.ip_to_int(request.client_ip)    
    try:
        PostDiggLog.objects.get(post__id = post.id, ip = client_ip_int)
        is_digged = True
    except(PostDiggLog.DoesNotExist):
        pass
    except:
        logs.write(traceback)     

    # comment form
    comment_form = CommentForm()
    if request.is_logined:
        comment_form = CommentForm({
                                     'name' : request.current_profile.user.realname,
                                     'url' : request.current_profile.get_url(),
                                     'email' : request.current_profile.user.email,
                                     'body' : '',
                                    })        
    comments = []
    try:
        comments = Comment.objects.filter(post__id = post.id).order_by('addtime')
    except:
        logs.write(traceback)

    data = {
            'current_profile': request.current_profile,
            'owner' : owner,
            'post' : post,
            'is_digged': is_digged,
            'comment_form' : comment_form,
            'comments' : comments,
            }

    template = _get_template_path('post.html')

    return view.out_page(template,data)

def post_digg_add(request):
    """
    summary:
        推荐文章ajax调用,不用返回
    """
    state = ExecuteState()
    
    # get params
    post_id = convert.to_int(view.get_form_val(request,"id"))
    if(post_id == -1):
        state.success = False
        return view.out_text(state.str())
    
    client_ip_int = convert.ip_to_int(request.client_ip)
    try:
        # check exist digg
        digg_log = PostDiggLog.objects.get(post__id = post_id, ip = client_ip_int)
        
        state.message = '只能推荐一次'
        state.success = False
        state.mark = "twice"
        return view.out_text(state.str())
    except(PostDiggLog.DoesNotExist):
        try:
            # update post
            post = Post.objects.get(id = post_id)        
            post.digg_count = post.digg_count + 1
            post.save()
            
            # save digg log
            digg_log = PostDiggLog(post = post,ip = client_ip_int)
            digg_log.save()
        except:
            state.success = False
            logs.write(traceback)
    except:
        state.success = True
        logs.write(traceback)
        
    return view.out_text(state.str())

def post_comment_add(request):
    """
    summary:
        发表评论AJAX调用
    """
    state = ExecuteState()
    
    # get params
    post_id = convert.to_int(view.get_form_val(request,"id"))
    name = view.get_form_val(request,'name')
    url = view.get_form_val(request,'url')
    email = view.get_form_val(request,'email')
    body = view.get_form_val(request,'body')
    follow = False
    if view.get_form_val(request,'follow') == '1':
        follow = True
    
    if(post_id == -1):
        state.success = False
        state.message = errorinfos.unknow
        return view.out_text(state.str())
    
    client_ip_int = convert.ip_to_int(request.client_ip)

    post = Post.objects.get(id = post_id)
    
    if not post:   
        state.message = errorinfos.unknow
        return view.out_text(state.str())
    
    try:             
        # save digg log
        comment = Comment(post = post, profile = request.current_profile ,name = name,url = url, email = email, body = body ,ip = client_ip_int, follow = follow)
        state = comment.check()
        
        if not state.success:
            return view.out_text(state.str())
        
        comment.save()
        state.success = True        
        
        face = ''
        if comment.profile:
            face = comment.profile.face
        state.dict = {
                        'id' : comment.id,
                        'addtime' : comment.addtime.strftime('%Y-%m-%d %H:%M'),
                        'timesince' :defaultfilters.timesince(comment.addtime),
                        'body' : comment.body,
                        'user' : {
                                  'realname' : comment.name,
                                  'url' : comment.url,
                                  'face' : pagebase.face24(face),
                                  },                              
                    }
        
    except:
        state.success = False
        state.message = errorinfos.unknow
        logs.write(traceback)        

    
    
    return view.out_text(state.str())

def admin(request):
    """
    summary:
        user admin home
    params:
        request
    author:
        Jason Lee <huacnlee@gmail.com>
    """    
    total = {
            'comment_count' : 0,
            'post_count' : 0,
            'draf_count' : 0,
            }

    # get recent comments
    comments = []
    try:
        comments = Comment.objects.filter(post__profile__user__id = request.current_profile.user.id).order_by('-addtime')
        total['post_count'] = Post.objects.filter(profile__user__id = request.current_profile.user.id,status = 1).count()
        total['draf_count'] = Post.objects.filter(profile__user__id = request.current_profile.user.id,status = 0).count()
        total['comment_count'] = comments.count()
        comments = comments[0:10]
    except:
        logs.write(traceback)
            
        
    data = {
            'current_profile' : request.current_profile,
            'comments' : comments,
            'total' : total,
            'current_menu' : 'home',
            }
    template = _get_template_path('admin/home.html')
    return view.out_page(template,data)
    
def admin_post_add(request):
    """
    summary:
        用户后台发表文章
    params:
        request object request param
    author:
        Jason Lee <huacnlee@gmail.com>
    """
    categorys = []
    
    try:
        categorys = Category.objects.filter(profile__user__id = request.current_profile.user.id).order_by('sort')
    except:
        logs.write(traceback)
    data = {
            'current_profile' : request.current_profile,
            'current_menu' : 'post_add',
            'categorys' : categorys,
            }
    template = _get_template_path('admin/post-add.html')
    return view.out_page(template,data)
    